package com.example.websocket.component;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author ASUS
 */

@ServerEndpoint(value = "/webserver/{username}")
@Component
public class WebSocketService {
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessionMap.put(username, session);
        System.out.println("有新的用户加入:" + username+"----" + "当前用户数" + sessionMap.size());
        sendMessageToAll("新成员：" + username);
    }
    @OnClose
    public void onClose(@PathParam("username") String username) {
        sessionMap.remove(username);
        System.out.println("移除了" + username + "当前用户人数：" + sessionMap.size());
    }

    /**
     * 当客户端发来消息的时候
     * @param session 表示当前用户
     * @Param username 表示当前用户
     * @Param message 所有的要发给谁
     * */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        String msg = null;
        String toUser = null;
        sendMessage(username, toUser, msg);
    }

    @OnError
    public void onError(Session session, Throwable error) {

    }

    private void sendMessage(String username,String toUser, String msg) {
        try {
            Session end = sessionMap.get(toUser);
            end.getBasicRemote().sendText(msg);
            System.out.println(username+"发送了："+msg);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("发送失败");
        }

    }
    private void sendMessageToAll(String msg) {
        try {
            for (Session session : sessionMap.values()) {
                System.out.println("正在发送全员消息-->" + "--msg:" + msg);
                session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            System.out.println("发送失败");
            e.printStackTrace();
        }
    }

    public  String getUserBySession(Map<String,Session> map,Session session){
        String key = null;
        //Map,HashMap并没有实现Iteratable接口.不能用于增强for循环.
        for(String Key: map.keySet()){
            if(map.get(Key).equals(session)){
                key = Key;
                return key;
            }
        }
        return key;
        //这个key肯定是最后一个满足该条件的key.
    }

}
